package com.yang.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.model.common.dtos.ResultCode;
import com.yang.common.exception.BusinessException;
import com.yang.user.mapper.AppUserMapper;
import com.yang.user.service.AppUserService;
import com.yang.model.user.dtos.LoginDto;
import com.yang.model.user.pojos.AppUser;
import com.yang.common.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: Billyang
 * @date: 2024/9/22 14:28
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {
    @Override
    public Map<String,Object> login(LoginDto dto) {
        //1.正常登录（手机号+密码登录）
        if (!StringUtils.isBlank(dto.getPhone()) && !StringUtils.isBlank(dto.getPassword())) {
            //1.1查询用户
            AppUser appUser = getOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getPhone, dto.getPhone()));
            if (appUser == null) {
                throw BusinessException.of(ResultCode.USER_NOT_EXIST);
            }

            //1.2 比对密码
            String salt = appUser.getSalt();
            String password = dto.getPassword();
            password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!password.equals(appUser.getPassword())) {
                throw BusinessException.of(ResultCode.PASSWORD_ERROR);
            }
            //1.3 返回数据  jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(appUser.getId().longValue()));
            appUser.setSalt("");
            appUser.setPassword("");
            map.put("user", appUser);
            return map;
        } else {
            //2.游客  同样返回token  id = 0
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return map;
        }
    }
}
